package com.cr4y0n.crayonpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cr4y0n.crayonpicturebackend.constant.UserConstant;
import com.cr4y0n.crayonpicturebackend.exception.ErrorCode;
import com.cr4y0n.crayonpicturebackend.exception.ThrowUtils;
import com.cr4y0n.crayonpicturebackend.model.dto.user.UserQueryRequest;
import com.cr4y0n.crayonpicturebackend.model.entity.User;
import com.cr4y0n.crayonpicturebackend.model.enums.UserRoleEnum;
import com.cr4y0n.crayonpicturebackend.model.vo.LoginUserVO;
import com.cr4y0n.crayonpicturebackend.model.vo.UserVO;
import com.cr4y0n.crayonpicturebackend.service.UserService;
import com.cr4y0n.crayonpicturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 针对表【user(用户)】的数据库操作Service实现
 *
 * @author cr4y0n
 * @version 1.0.0
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 用户注册
     *
     * @param userAccount   用户账号
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 返回新注册用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8, ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR, "用户密码与确认密码不一致");

        // 2. 检查用户账号是否和数据库中已有账号重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = this.baseMapper.selectCount(queryWrapper);
        ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR, "注册账号重复");

        // 3. 密码加密
        String encryptedPassword = getEncryptedPassword(userPassword);

        // 4.插入数据到数据库中
        User user = User.builder()
                .userAccount(userAccount)
                .userPassword(encryptedPassword)
                .userName("无名")
                .userRole(UserRoleEnum.USER.getValue())
                .build();
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        // 5. 返回新注册用户id
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账号
     * @param userPassword 用户密码
     * @param request      请求
     * @return 用户已登录视图（脱敏）
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "用户名密码不能为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "用户密码过短");

        // 2. 对用户传递的密码进行加密
        String encryptedPassword = getEncryptedPassword(userPassword);

        // 3. 查询数据库中的用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount)
                .eq("userPassword", encryptedPassword);
        User user = this.getOne(queryWrapper);
        ThrowUtils.throwIf(BeanUtil.isEmpty(user), ErrorCode.PARAMS_ERROR, "用户不存在或者密码错误");

        // 4. 保存用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        return getLoginUserVO(user);
    }

    /**
     * 获取已脱敏用户视图信息
     *
     * @param user 用户信息
     * @return 用户视图信息（已脱敏）
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        return BeanUtil.copyProperties(user, LoginUserVO.class);
    }

    /**
     * 获取登录用户信息
     *
     * @param request HTTP请求
     * @return 用户信息
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 1. 判断是否登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(BeanUtil.isEmpty(currentUser), ErrorCode.NOT_LOGIN_ERROR);

        // 2.从数据库中重新查询一遍数据看是否更新
        currentUser = this.getById(currentUser.getId());
        ThrowUtils.throwIf(BeanUtil.isEmpty(currentUser), ErrorCode.NOT_LOGIN_ERROR);
        return currentUser;
    }

    /**
     * 加密用户密码
     *
     * @param userPassword 用户密码
     * @return 用户密码进行加密后的密文
     */
    @Override
    public String getEncryptedPassword(String userPassword) {
        final String SALT = "crayon";
        return DigestUtil.md5Hex(userPassword + SALT);
    }

    /**
     * 用户退出登录
     *
     * @param request HTTP请求
     * @return 是否成功
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 1. 判断是否登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(BeanUtil.isEmpty(userObj), ErrorCode.OPERATION_ERROR, "未登录");

        // 2. 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取用户视图（已脱敏）
     *
     * @param user 用户信息
     * @return 用户视图（已脱敏）
     */
    @Override
    public UserVO getUserVO(User user) {
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    /**
     * 获取脱敏后的用户列表
     *
     * @param userList 用户信息列表
     * @return 用户视图列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取查询条件
     *
     * @param userQueryRequest 用户查询请求
     * @return 查询条件
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(BeanUtil.isEmpty(userQueryRequest), ErrorCode.PARAMS_ERROR, "请求参数为空");
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(StrUtil.isNotEmpty(userRole), "userRole", userRole);
        queryWrapper.like(ObjUtil.isNotEmpty(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotEmpty(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotEmpty(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 确认是否为管理员
     *
     * @param user 用户
     * @return 返回是否为管理员
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
}




